package com.bj58.groupbuy.action.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Properties;
import java.util.regex.Pattern;


public class StringUtil {

	public static String urlDecode(String content, String charset) {
		try {
			if(content!=null){
				return URLDecoder.decode(content, charset);
			}else {
				return "";
			}
		} catch (UnsupportedEncodingException ex) {
			return content;
		}
	}

	public static String urlEncode(String content, String charset) {
		try {
			return URLEncoder.encode(content, charset);
		} catch (UnsupportedEncodingException ex) {
			return content;
		}
	}

	public static String encode(String source, String from, String to) {
		byte[] bts;
		try {
			bts = source.getBytes(from);
			return new String(bts, to);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String parseCharacterEncoding(String contentType) {
		if (contentType == null)
			return (null);
		int start = contentType.indexOf("charset=");
		if (start < 0)
			return (null);
		String encoding = contentType.substring(start + 8);
		int end = encoding.indexOf(';');
		if (end >= 0)
			encoding = encoding.substring(0, end);
		encoding = encoding.trim();
		if ((encoding.length() > 2) && (encoding.startsWith("\""))
				&& (encoding.endsWith("\"")))
			encoding = encoding.substring(1, encoding.length() - 1);
		return (encoding.trim());

	}

	public static boolean isEmpty(String str) {
		return (str == null) || (str.equals(""));
	}

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String toHexString(byte[] buf) {
		return toHexString(buf, null, Integer.MAX_VALUE);
	}

	public static String toHexString(byte[] buf, String sep, int lineLen) {
		if (buf == null)
			return null;
		if (lineLen <= 0)
			lineLen = Integer.MAX_VALUE;
		StringBuffer res = new StringBuffer(buf.length * 2);
		for (int i = 0; i < buf.length; i++) {
			int b = buf[i];
			res.append(HEX_DIGITS[(b >> 4) & 0xf]);
			res.append(HEX_DIGITS[b & 0xf]);
			if (i > 0 && (i % lineLen) == 0)
				res.append('\n');
			else if (sep != null && i < lineLen - 1)
				res.append(sep);
		}
		return res.toString();
	}

	private static final int charToNibble(char c) {
		if (c >= '0' && c <= '9') {
			return c - '0';
		} else if (c >= 'a' && c <= 'f') {
			return 0xa + (c - 'a');
		} else if (c >= 'A' && c <= 'F') {
			return 0xA + (c - 'A');
		} else {
			return -1;
		}
	}

	public static byte[] fromHexString(String text) {
		text = text.trim();
		if (text.length() % 2 != 0)
			text = "0" + text;
		int resLen = text.length() / 2;
		int loNibble, hiNibble;
		byte[] res = new byte[resLen];
		for (int i = 0; i < resLen; i++) {
			int j = i << 1;
			hiNibble = charToNibble(text.charAt(j));
			loNibble = charToNibble(text.charAt(j + 1));
			if (loNibble == -1 || hiNibble == -1)
				return null;
			res[i] = (byte) (hiNibble << 4 | loNibble);
		}
		return res;
	}

	public static String join(String[] arr, String split) {
		if (arr != null && arr.length > 0) {
			StringBuilder stringBuilder = new StringBuilder();
			for (String s : arr) {
				stringBuilder.append(s).append(split);
			}
			stringBuilder.delete(stringBuilder.length() - split.length(),
					stringBuilder.length());
			return stringBuilder.toString();
		} else {
			return "";
		}
	}
	
	public static String join(Object[] arr, String split) {
		if (arr != null && arr.length > 0) {
			StringBuilder stringBuilder = new StringBuilder();
			for (Object s : arr) {
				stringBuilder.append(String.valueOf(s)).append(split);
			}
			stringBuilder.delete(stringBuilder.length() - split.length(),
					stringBuilder.length());
			return stringBuilder.toString();
		} else {
			return "";
		}
	}
	
	public static Properties parseProperties(String data , String split){
		Properties properties = new Properties();
		if(!StringUtil.isEmpty(split) && !StringUtil.isEmpty(data)){
			for (String dd : data.split(split)) {
				String[] d = dd.split("=");
				if(d.length==2){
					properties.put(d[0], d[1]);
				}
			}
		}
		return properties;
	}
	/**
	 * 去标签处理
	 * create by yanjr at 2010-08-06 11:20
	 */
	public static String splitAndFilterString(String input) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		return str;

	}
	
	/**
	 * 获得非null字符串
	 * @param theStr
	 * @return
	 */
	public static String doNullStr(String theStr){
		return theStr==null?"":theStr;
	}
	
	/**
	 * 数字字符串相加并返回字符串类型
	 * */
	public static String StrAddstr(String str1,String str2)
	 {
		Pattern pattern = Pattern.compile("[0-9]*"); 
		Pattern pattern2=Pattern.compile("[0-9]*(\\.?)[0-9]*");
	    if(pattern.matcher(str1).matches()&&pattern.matcher(str2).matches())  
	    {
	    	return String.valueOf(Integer.parseInt(str1)+Integer.parseInt(str2));
	    }else if(pattern2.matcher(str1).matches()&&pattern2.matcher(str2).matches())  
	    {
	    	return String.valueOf(Float.parseFloat(str1)+Float.parseFloat(str2));
	    }
	    System.out.println("数字字符串相加时出错，"+str1+"和"+str2+"不是浮点型或者整形！");
	    return null;
	 } 	 
	/**
	 * 数字字符串相除并返回字符串类型
	 * 使用浮点型相除，避免整形相除后为0
	 * */
	public static String StrSubstr(String str1,String str2)
	 {
		Pattern pattern = Pattern.compile("[0-9]*"); 
		Pattern pattern2=Pattern.compile("[0-9]*(\\.?)[0-9]*");
	   /* if(pattern.matcher(str1).matches()&&pattern.matcher(str2).matches())  
	    {
	    	if(Integer.parseInt(str2)==0)
	    	{
	    		return "0";
	    	}
	    	return String.valueOf(Integer.parseInt(str1)/Integer.parseInt(str2));
	    }else*/ if((pattern2.matcher(str1).matches()&&pattern2.matcher(str2).matches())||(pattern.matcher(str1).matches()&&pattern.matcher(str2).matches()))  
	    {
	    	if(Float.parseFloat(str2)-0<0.0001)
	    	{
	    		return "0";
	    	}
	    	return String.valueOf(Float.parseFloat(str1)/Float.parseFloat(str2));
	    }
	    System.out.println("数字字符串相除时出错，"+str1+"和"+str2+"不是浮点型或者整形！");
	    return null;
	 } 	 
}
